properties([
   parameters([
      booleanParam(name: 'FORCE_REBUILD', defaultValue: false, description: 'Force Rebuild'),
      string(name: 'MAX_WORKES_PER_NODE', defaultValue: '1', description: ''),
      booleanParam(name: 'FORCE_REBUILD_LIBRARY', defaultValue: false, description: 'Force rebuild library when build manifest'),
    ])
 ])

def projectName = 'Test'
// 对于 master 而言，mount 路径就是本地路径
def originProjectDir = config.mountProjectDir(projectName)
// 所有玩家都能读出来的路径，会写进 distribute.manifest 中
def sharedProjectDir = config.sharedProjectDir(projectName)

def masterNodeName = config.masterNodeName()

def shouldRebuildLibrary()
{
   return config.shouldRebuild() || params.FORCE_REBUILD_LIBRARY
}

def rebuildLibraryArgvs()
{
   if(shouldRebuildLibrary())
      return " -rebuildlibrary "
   else
      return ""
}

node("${masterNodeName}")
{
   stage("Prepare")
   {
      // 创建Log目录
      def logDir = "${originProjectDir}/${config.distributeLogDir()}" 
      sh "if [ ! -d ${logDir} ]; then ( mkdir -p ${logDir} ) fi"

      // 拷贝unity程序
      config.copyUnityDir("${masterNodeName}")

      // 开始前，删除所有可能因上次编译错误或者手动停止的lock
      utils.deleteAllLockFiles(projectName)

      // 准备工程
      utils.prepareProjectForAllNode(projectName, "distribute-test-worker", shouldRebuildLibrary())
   }

   stage('Master: Build Manifest')
   {
      def logDir = "${originProjectDir}/${config.distributeLogDir()}"
      def logFilePath = "${logDir}/distribute${config.buildName()}.log"

      def forceRebuild = ""
      if(params.FORCE_REBUILD)
      {
         forceRebuild = " -forceRebuild "
      }

      // 这里一定要用原始工程目录，因为，之后的打包数据：均依赖该路径数据
      sh """
         ${config.localUnityPath(masterNodeName)} -quit -batchmode   \
         -projectPath ${originProjectDir}                            \
         -executeMethod AssetBundleDistributer.Run                   \
         -distributedMaster ${sharedProjectDir}                      \
         -logfile ${logFilePath}                                     \
         ${rebuildLibraryArgvs()} ${forceRebuild}
      """
   }

   stage('Master: Distribute Tasks')
   {
      // 读清单文件，以获得要编译的ab包数量（即work数量）
      def mainfestFile = "${originProjectDir}/distribute.manifest"
      datas = readYaml (file: "${mainfestFile}")

      echo mainfestFile

      def workCount = datas.WorkCount
      int paramsWorkesPerNode = params.MAX_WORKES_PER_NODE
      utils.distributeTask(projectName, "distribute-test-worker", workCount, paramsWorkesPerNode)

      utils.waitForAllTasksFinished(projectName)
   }
}
